package com.jml.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jml.base.BaseService;
import com.jml.entity.JmlConfigEntity;
import com.jml.entity.JmlConfigInfoEntity;
import com.jml.mapper.JmlConfigInfoMapper;
import com.jml.mapper.JmlConfigMapper;
import com.jml.mapper.JmlConfigUnionMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@CrossOrigin
public class ConfigService extends BaseService {
    @Autowired
    private JmlConfigMapper jmlConfigMapper;
    @Autowired
    private JmlConfigInfoMapper jmlConfigInfoMapper;
    @Autowired
    private JmlConfigUnionMapper jmlConfigUnionMapper;

    /**
     * md5 比对配置文件内容是否发生变化，如果发生了变化，就返回最新的配置文件
     *
     * @param name：服务名字
     * @param md5：客户端服务配置文件的md5
     * @return
     */
    @GetMapping("/md5Comparison")
    public ResponseEntity md5Comparison(String name, String md5) {
        if (StringUtils.isEmpty(name)) {
            return setResultFail("error :name is null ");
        }
        if (StringUtils.isEmpty(md5)) {
            return setResultFail("error :md5 is null ");
        }
        JmlConfigEntity jmlConfigEntity = jmlConfigMapper.getByConfigName(name);
        if (jmlConfigEntity == null) {
            return setResultFail("The profile content is not configured on the server ");
        }
        if (jmlConfigEntity.getMd5().equals(md5)) {
            return setResultOk("ok");
        }
        JSONObject data = resultData(jmlConfigEntity);
        return data != null ? setResultOk("配置文件内容发生了变化", data, 201) :
                setResultFail("The profile content is not configured on the server ");

    }

    /**
     * 根据服务名称读取配置文件
     *
     * @param name
     * @return
     */
    @GetMapping("/getConfig")
    public ResponseEntity getConfig(String name) {
        if (StringUtils.isEmpty(name)) {
            return setResultFail("error :name is null ");
        }
        // 根据该服务名称查找db 配置文件内容
        JmlConfigEntity jmlConfigEntity = jmlConfigMapper.getByConfigName(name);
        if (jmlConfigEntity == null) {
            return setResultFail("The profile content is not configured on the server ");
        }
        //获取配置文件
        JSONObject data = resultData(jmlConfigEntity);
        return data != null ? setResultOk("ok", data) : setResultFail("The profile content is not configured on the server ");
    }

    private JSONObject resultData(JmlConfigEntity jmlConfigEntity) {
        // 根据配置文件查找详细配置文件内容
        Long confId = jmlConfigEntity.getId();
        List<JmlConfigInfoEntity> jmlConfigInfoList = jmlConfigInfoMapper.getByConfigId(confId);
        if (jmlConfigInfoList == null || jmlConfigInfoList.size() == 0) {
            return null;
        }
        JSONObject data = new JSONObject();
        data.put("name", jmlConfigEntity.getName());
        data.put("configId", confId);
        JSONArray jsonArray = new JSONArray();
        jmlConfigInfoList.forEach((t) -> {
            JSONObject configInfo = new JSONObject();
            configInfo.put("key", t.getKey());
            configInfo.put("value", t.getValue());
            jsonArray.add(configInfo);
        });
        data.put("config", jsonArray);
        data.put("md5", jmlConfigEntity.getMd5());
        return data;
    }


    /**
     * 查询所有配置文件内容
     *
     * @return
     */
    @GetMapping("/configList")
    public ResponseEntity configList() {
        return setResultOk("查询数据成功", jmlConfigUnionMapper.configList());
    }

    /**
     * http://127.0.0.1:8099/updateConfig?id=1&value=yushengjun644 修改配置文件内容
     *
     * @param id：jml_config_info表的id
     * @param value
     * @return
     */
    @PostMapping("/updateConfig")
    public ResponseEntity updateConfig(Long id, String value) {
        if (id == null) {
            return setResultFail("id is null");
        }
        if (StringUtils.isEmpty(value)) {
            return setResultFail("value is null");
        }
        JmlConfigInfoEntity jmlConfigInfo = jmlConfigInfoMapper.getById(id);
        if (jmlConfigInfo == null) {
            return setResultFail("没有查找到该配置");
        }
        jmlConfigInfo.setValue(value);
        int updateConfig = jmlConfigInfoMapper.updateById(value, id);
        if (updateConfig == 0) {
            return setResultFail("更新失败!");
        }
        // 更新md5
        int updateMd5Result = jmlConfigMapper.updateMd5(System.currentTimeMillis() + "", jmlConfigInfo.getConfigId());
        return updateMd5Result > 0 ? setResultOk("更新成功", jmlConfigUnionMapper.configList()) : setResultFail("更新失败!");
    }
}

